package br.com.sgc.session;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

import br.com.sgc.dao.ClienteDao;
import br.com.sgc.entities.geral.Cliente;
import br.com.sgc.entities.geral.PacienteAnimal;
import br.com.sgc.entities.veterinaria.Animal;
import br.com.sgc.enuns.TipoOrdenacao;
import br.com.sgc.exception.ValidacaoException;
import br.com.sgc.helper.ValidadorCNPJCPFUtil;

@Stateless
public class ClienteSession extends GenericSession<Cliente>{

	private static final long serialVersionUID = 3682794245694671915L;
	
	@EJB private ClienteDao dao;
	
	@EJB private PacienteAnimalSession pacienteAnimalSession;
	
	@Override
	public Cliente save(Cliente t) throws ValidacaoException {
		for(Animal animal: t.getAnimal()){
			PacienteAnimal paciente = new PacienteAnimal();
			paciente.setAnimal(animal);
			paciente.setClinica(t.getClinica());
			paciente.setPlanoSaude(null);
			pacienteAnimalSession.save(paciente);
		}
		return super.save(t);
	}
	
	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public Cliente update(Cliente t) throws ValidacaoException {
		for(Animal animal: t.getAnimal()){
			PacienteAnimal paciente = pacienteAnimalSession.findPacienteByAnimalId(animal.getId());
			animal.setDonoAnimal(t);
			if(paciente != null){
				paciente.setAnimal(animal);
				paciente.setClinica(t.getClinica());
				paciente.setPlanoSaude(null);
			} else {
				paciente = new PacienteAnimal();
				paciente.setAnimal(animal);
				paciente.setClinica(t.getClinica());
				paciente.setPlanoSaude(null);
				animal.getPaciente().add(paciente);
			}
		}
		return dao.update(t, false);
	}
	
	public void validarCPF(String cpf) throws ValidacaoException {
		String erro = "";
		if (cpf == null || cpf.trim().equals("")) {
			erro +="Campo CPF precisa ser preenchido! <br />";
		} else if (!ValidadorCNPJCPFUtil.isCPFValido(cpf)) {
			erro +="O CPF informado � inv�lido! <br />";
		}
		if (erro != "") {
			throw new ValidacaoException(erro);
		}
	}
	
	@Override
	public List<Cliente> findAll(Cliente modelClass, Long clinicaId, Integer startPage,
			Integer maxPage, String orderField, Boolean initializeDependecies) {
		return dao.findAll(modelClass, clinicaId, startPage, maxPage, orderField, initializeDependecies);
	}
	
	public List<Cliente> findAll(Cliente modelClass, Long clinicaId, Integer startPage, Integer maxPage, String orderField, Boolean initializeDependecies, TipoOrdenacao tipoOrdenacao){
		return dao.findAll(modelClass, clinicaId, startPage, maxPage, orderField, initializeDependecies, tipoOrdenacao);
	} 
	
	@Override
	public Long count(Cliente modelClass, Long clinicaId){
		return dao.count(modelClass, clinicaId);
	}

}
